package com.wtwd.device.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.dao.SleepRecordMapper;
import com.wtwd.device.model.entity.SleepInfo;
import com.wtwd.device.model.entity.SleepRecord;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.SleepRecordService;
import com.wtwd.device.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author mjy
 * @date 2021/09/02
 * @description
 */
@Service
public class SleepRecordServiceImpl implements SleepRecordService {

    @Autowired
    private SleepRecordMapper sleepRecordMapper;


    @Override
    public RespEntity getDaysSleepRecord(Long deviceId, String startTime, String endTime) {
        List<SleepRecord> sleepRecords = sleepRecordMapper.getDaysSleepRecord(deviceId, startTime, endTime);
        if (sleepRecords != null && sleepRecords.size() > 0) {
            sleepRecords.stream().forEach(sleepRecord -> {
                sleepRecord.setSleepInfoList(JSONArray.parseArray(sleepRecord.getSleepInfo(), SleepInfo.class));
            });
        }
        return new RespEntity(RespCode.SUCCESS, sleepRecords);
    }

    @Override
    public RespEntity getMonthSleepRecord(Long deviceId, String month) {
        List<SleepRecord> sleepRecords = sleepRecordMapper.getMonthSleepRecord(deviceId, month);
        if (sleepRecords != null && sleepRecords.size() > 0) {
            sleepRecords.stream().forEach(sleepRecord -> {
                sleepRecord.setSleepInfoList(JSONArray.parseArray(sleepRecord.getSleepInfo(), SleepInfo.class));
            });
        }
        return new RespEntity(RespCode.SUCCESS, sleepRecords);
    }

    @Override
    public RespEntity addSleepRecord(SleepRecord sleepRecord) {
        String time = DateUtils.format(sleepRecord.getTime(), DateUtils.dateFormat5);
        SleepRecord sleepRecordOld = sleepRecordMapper.getSleepRecordByDeviceIdAndTime(sleepRecord.getDeviceId(), time);
        if (sleepRecordOld != null) {
            return new RespEntity(RespCode.TODAYS_DATA_ALREADY_EXIST);
        }
        sleepRecord.setSleepInfo(JSONArray.toJSONString(sleepRecord.getSleepInfoList()));
        sleepRecord.setUploadTime(new Date().getTime());
        Integer rest = sleepRecordMapper.addSleepRecord(sleepRecord);
        return new RespEntity(rest>0?RespCode.SUCCESS:RespCode.FAIL);
    }

    @Override
    public Integer clearSleepRecordByDate(String date) {
        return sleepRecordMapper.clearSleepRecordByDate(date);
    }

    @Override
    public SleepRecord getSleepRecordByDeviceIdAndTime(Long id, String time) {
        return sleepRecordMapper.getSleepRecordByDeviceIdAndTime(id,time);
    }

    @Override
    public Integer deleteSleepRecordByDeviceId(Long id) {
        return sleepRecordMapper.deleteSleepRecordByDeviceId(id);
    }

}
